<template>
  <el-dialog :visible.sync="dialogTableVisible" :append-to-body="true" :lock-scroll="false" :title="isEdit?'Edit':'Create'" width="900px" @close="handleCloseDetailDialog">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="left" label-width="100px" style="margin-left:50px;">

      <el-form-item :label="$t('table.area')" required>
        <el-select v-model="postForm.area" clearable placeholder="Please Chose" width="600px">
          <el-option v-for="item in areaList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('table.homemenu')">
            <el-cascader
              :placeholder="$t('placeholder.select')"
              v-model="postForm.homemenu_id"
              :options="categoryOptions"
              change-on-select
            ></el-cascader>
            <!-- <el-select v-model="temp.category_id" class="filter-item" :placeholder="$t('placeholder.select')">
              <el-option v-for="(item, index) in categoryOptions" :key="index" :label="item.name" :value="item.id" />
            </el-select> -->
      </el-form-item>

      <el-form-item :label="$t('adfiles.position')" required>
        <el-select v-model="postForm.positions" clearable placeholder="Please Chose" width="600px">
          <el-option v-for="item in positionList" :key="item.id" :label="item.name" :value="item.id"/>
        </el-select>
      </el-form-item>

      <el-form-item :label="$t('table.available')" prop="is_available" required>
        <el-radio-group v-model="postForm.is_available">
          <el-radio :label="1">{{ $t('table_element.available.on') }}</el-radio>
          <el-radio :label="0">{{ $t('table_element.available.un') }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label="$t('adfiles.sort')" prop="sort" >
        <el-col :span="20">
          <el-input v-model="postForm.sort" :label="$t('adfiles.sort')" type="number" min="1"/>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('adfiles.start_at')">
        <el-col :span="20">
          <el-form-item prop="start_at">
            <el-date-picker v-model="postForm.start_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <el-form-item :label="$t('adfiles.end_at')">
        <el-col :span="20">
          <el-form-item prop="end_at">
            <el-date-picker v-model="postForm.end_at" type="datetime" value-format="yyyy-MM-dd HH:mm:ss" format="yyyy-MM-dd HH:mm:ss" :placeholder="$t('placeholder.date')" style="width: 100%;"/>
          </el-form-item>
        </el-col>
      </el-form-item>

      <template>
        <el-tabs v-model="activeName">
          <el-tab-pane label="en" name="first" >
            <el-form-item :label="$t('adfiles.title')" prop="en_title" required>
              <el-col :span="20">
                <el-input v-model="postForm.en_title" :label="$t('adfiles.title')"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.description')" prop="en_description" >
              <el-col :span="20">
                <el-input v-model="postForm.en_description" :label="$t('adfiles.description')" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.image')" prop="en_image" >
              <el-col :span="20">

                <el-upload
                  :headers="header"
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="en_imageUrl" :src="en_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>

                <el-input v-model="postForm.en_image" :label="$t('adfiles.image')" type="hidden"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.link')" prop="en_link" >
              <el-col :span="20">
                <el-input v-model="postForm.en_link" :label="$t('adfiles.link')"/>
              </el-col>
            </el-form-item>

          </el-tab-pane>

          <el-tab-pane label="zh-ch" name="second">
            <el-form-item :label="$t('adfiles.title')" prop="cn_title">
              <el-col :span="20">
                <el-input v-model="postForm.cn_title" :label="$t('adfiles.title')"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.description')" prop="cn_description" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_description" :label="$t('adfiles.description')" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.image')" prop="cn_image" >
              <el-col :span="20">

                <el-upload
                  :headers="header"
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="cn_imageUrl" :src="cn_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>
                <el-input v-model="postForm.cn_image" :label="$t('adfiles.image')" type="hidden"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.link')" prop="cn_link" >
              <el-col :span="20">
                <el-input v-model="postForm.cn_link" :label="$t('adfiles.link')"/>
              </el-col>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="zh-hk" name="third">
            <el-form-item :label="$t('adfiles.title')" prop="hk_title" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_title" :label="$t('adfiles.title')"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.description')" prop="hk_description" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_description" :label="$t('adfiles.description')" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.image')" prop="hk_image" >
              <el-col :span="20">

                <el-upload
                  :headers="header"
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="hk_imageUrl" :src="hk_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>

                <el-input v-model="postForm.hk_image" :label="$t('adfiles.image')" type="hidden"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.link')" prop="hk_link" >
              <el-col :span="20">
                <el-input v-model="postForm.hk_link" :label="$t('adfiles.link')"/>
              </el-col>
            </el-form-item>

          </el-tab-pane>
          <el-tab-pane label="zh-tw" name="fourth">
            <el-form-item :label="$t('adfiles.title')" prop="tw_title" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_title" :label="$t('adfiles.title')"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.description')" prop="tw_description" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_description" :label="$t('adfiles.description')" type="textarea"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.image')" prop="tw_image" >
              <el-col :span="20">

                <el-upload
                  :headers="header"
                  :show-file-list="false"
                  :on-success="handleImagesSuccess"
                  :action="getUploadImageUrl()"
                  class="avatar-uploader"
                  name = "img">
                  <img v-if="tw_imageUrl" :src="tw_imageUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"/>
                </el-upload>

                <el-input v-model="postForm.tw_image" :label="$t('adfiles.image')" type="hidden"/>
              </el-col>
            </el-form-item>

            <el-form-item :label="$t('adfiles.link')" prop="tw_link" >
              <el-col :span="20">
                <el-input v-model="postForm.tw_link" :label="$t('adfiles.link')"/>
              </el-col>
            </el-form-item>

          </el-tab-pane>
        </el-tabs>
      </template>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleCloseDetailDialog">{{ $t('table.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm('postForm')">{{ $t('table.submit') }}</el-button>
    </div>
  </el-dialog>

</template>
<script>

import { fetchCategoryTree } from '@/api/homemenu'
import adApi from '@/api/ad/ad'
import i18n from '@/lang/index'
import { getUploadImageUrl } from '@/utils'
import { getToken } from '@/utils/auth'

const defaultForm = {
  area: 96,
  homemenu_id: [],
  is_available: 1,
  type: '',
  hits: '',
  start_at: '',
  end_at: '',
  sort: 999999999,
  positions: '',

  en_title: '',
  en_description: '',
  en_image: '',
  en_link: '',
  en_imgpath: '',

  cn_title: '',
  cn_description: '',
  cn_image: '',
  cn_link: '',
  cn_imgpath: '',

  hk_title: '',
  hk_description: '',
  hk_image: '',
  hk_link: '',
  hk_imgpath: '',

  tw_title: '',
  tw_description: '',
  tw_image: '',
  tw_link: '',
  tw_imgpath: ''

}

export default {
  name: 'Detail',
  data() {
    return {
      header:{
        'X-Token': getToken()
      },
      isEdit: false,
      activeName: 'first',
      postForm: Object.assign({}, defaultForm),
      rules: {
      },
      areaList: [],
      en_imageUrl: '',
      cn_imageUrl: '',
      hk_imageUrl: '',
      tw_imageUrl: '',
      recordid: 0,
      dialogTableVisible: false,
      positionList: [],
      categoryOptions: [],
    }
  },
  computed: {
    lang() {
      return this.$store.getters.language
    }
  },
  created() {
    this.getCategoryList()
    if (this.isEdit) {
      const id = this.editId || (this.$route.params && this.$route.params.id)
      this.showRecord(id)
    } else {
      this.postForm = Object.assign({}, defaultForm)
    }
  },

  mounted() {

  },

  methods: {
    showRecord(id) {
      adApi.showRecord(id).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.postForm = serviceResponse.data.record
          this.positionList = serviceResponse.data.positionList
          this.en_imageUrl = this.postForm.en_image.indexOf('http') > -1 || this.postForm.en_image.indexOf('https') > -1 ? this.postForm.en_image : this.postForm.imageDomain + this.postForm.en_image
          this.cn_imageUrl = this.postForm.cn_image.indexOf('http') > -1 || this.postForm.cn_image.indexOf('https') > -1 ? this.postForm.cn_image : this.postForm.imageDomain + this.postForm.cn_image
          this.hk_imageUrl = this.postForm.hk_image.indexOf('http') > -1 || this.postForm.hk_image.indexOf('https') > -1 ? this.postForm.hk_image : this.postForm.imageDomain + this.postForm.hk_image
          this.tw_imageUrl = this.postForm.tw_image.indexOf('http') > -1 || this.postForm.tw_image.indexOf('https') > -1 ? this.postForm.tw_image : this.postForm.imageDomain + this.postForm.tw_image
        }
      }).catch(err => {
        console.log(err)
      })
    },

    handleCreateRecord() {
      const params = {
        lang: i18n.locale
      }
      adApi.createRecord(params).then(response => {
        const serviceResponse = response.data
        if (serviceResponse.code === 0) {
          this.positionList = serviceResponse.data.positionList
        }
      }).catch(err => {
        console.log(err)
      })
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.postForm.lang = i18n.locale

          if (this.editId > 0) {
            adApi.updateRecord(this.editId, this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: 'success!'
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: 'error!'
                })
              }
            })
          } else {
            adApi.storeRecord(this.postForm).then(response => {
              const serviceResponse = response.data
              if (serviceResponse.code === 0) {
                this.$message({
                  type: 'success',
                  message: 'success!'
                })
                this.handleCloseDetailDialog()
              } else {
                this.$message({
                  type: 'error',
                  message: 'error!'
                })
              }
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    handleImagesSuccess(res, file) {
      if (res.code === 0) {
        if (this.activeName === 'first') {
          this.postForm.en_image = res.data.paths[0].path
          this.en_imageUrl = (res.data.paths[0].path.indexOf('http')==0 || res.data.paths[0].path.indexOf('https')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
        if (this.activeName === 'second') {
          this.postForm.cn_image = res.data.paths[0].path
          this.cn_imageUrl = (res.data.paths[0].path.indexOf('http')==0 || res.data.paths[0].path.indexOf('https')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
        if (this.activeName === 'third') {
          this.postForm.hk_image = res.data.paths[0].path
          this.hk_imageUrl = (res.data.paths[0].path.indexOf('http')==0 || res.data.paths[0].path.indexOf('https')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
        if (this.activeName === 'fourth') {
          this.postForm.tw_image = res.data.paths[0].path
          this.tw_imageUrl = (res.data.paths[0].path.indexOf('http')==0 || res.data.paths[0].path.indexOf('https')==0) ? res.data.paths[0].path : res.data.imageDomain + '/' + res.data.paths[0].path
        }
      } else {
        alert(res.data.msg)
      }
    },
    handShowDetailDialog(id) {
      if (id > 0) {
        this.isEdit = true
        this.editId = id
        this.showRecord(id)
      } else {
        this.isEdit = false
        this.editId = 0
        this.handleCreateRecord()
        this.postForm = Object.assign({}, defaultForm)
      }
      this.getAreaOptions()
      this.dialogTableVisible = true
    },
    handleCloseDetailDialog() {
      this.resetForm('postForm')
      this.editId = 0
      this.$emit('indexRecord')
      this.en_imageUrl = ''
      this.cn_imageUrl = ''
      this.hk_imageUrl = ''
      this.tw_imageUrl = ''
      this.activeName = 'first'
      this.dialogTableVisible = false
    },
    getCategoryList() {
      fetchCategoryTree().then(response => {
        var data = response.data
        this.categoryOptions = data.data
      });
    },
    getAreaOptions() {
      this.areaList = this.$store.state.locale.areas
    },
    getUploadImageUrl() {
      return getUploadImageUrl()
    }

  }

}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    max-width: 178px;
    max-height: 178px;
    display: block;
  }
</style>
